package com.sign2024.sign2024project.signBase.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sign2024.sign2024project.signBase.JjGlobalDataStore;
import com.sign2024.sign2024core.common.CommonResult;
import com.sign2024.sign2024core.common.annotation.Log;
import com.sign2024.sign2024core.common.constants.CommonConstants;
import com.sign2024.sign2024core.common.exeception.CommonException;
import com.sign2024.sign2024core.common.utils.ExcelStyleUtils;
import com.sign2024.sign2024project.capitalconstruction.controller.ExcelType.JJProgectWriteHandler;
import com.sign2024.sign2024project.capitalconstruction.controller.ExcelType.JJProgectWriteHandlerColour;
import com.sign2024.sign2024project.capitalconstruction.vo.JjProgectVo;
import com.sign2024.sign2024project.signBase.ExcelType.GcSignBaseHandler;
import com.sign2024.sign2024project.signBase.ExcelType.GcSignBaseHandlerColour;
import com.sign2024.sign2024project.signBase.ExcelType.WzSignBaseHandler;
import com.sign2024.sign2024project.signBase.ExcelType.WzSignBaseHandlerColour;
import com.sign2024.sign2024project.signBase.GlobalDataStore;
import com.sign2024.sign2024project.signBase.WzGlobalDataStore;
import com.sign2024.sign2024project.signBase.entry.SignBase;
import com.sign2024.sign2024project.signBase.param.BaseParam;
import com.sign2024.sign2024project.signBase.service.SignBaseService;
import com.sign2024.sign2024project.signBase.vo.GCBaseVo;
import com.sign2024.sign2024project.signBase.vo.WzBaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 评标基地
 *
 * @author yujie
 * @data 2024/11/18 16:23
 */
@Api(tags = "评标基地")
@RestController
@RequestMapping("/api/base")
public class SignBaseController {

    @Resource
    private SignBaseService signBaseService;

    @Autowired
    private GlobalDataStore globalDataStore;

    @Autowired
    private JjGlobalDataStore jjGlobalDataStore;

    @Autowired
    private WzGlobalDataStore wzGlobalDataStore;

    @Log(title = "评标基地", businessType = "查询")
    @ApiOperation(value = "分页查询评标室信息", notes = "分页查询评标室信息")
    @PostMapping("/page")
    public CommonResult<SignBase> page(BaseParam param) {
        Page<SignBase> page = signBaseService.pageSignBase(param);
        return CommonResult.success(page);
    }

    @Log(title = "评标基地", businessType = "添加")
    @ApiOperation(value = "添加评标室信息", notes = "添加评标室信息")
    @PostMapping("/add")
    public CommonResult add(SignBase signBase) {
        signBaseService.insertSignBase(signBase);
        return CommonResult.success();
    }

    @Log(title = "评标基地", businessType = "更新")
    @ApiOperation(value = "修改评标室信息", notes = "修改评标室信息")
    @PostMapping("/save")
    public CommonResult saveDefault(SignBase signBase) {
        signBaseService.updateSignBase(signBase);
        return CommonResult.success();
    }


    @ApiOperation(value = "通过主键删除数据", notes = "通过主键删除数据")
    @Log(title = "评标基地", businessType = "删除")
    @PostMapping("/delete")
    public CommonResult<Boolean> deleteById(Integer id) {
        return CommonResult.success(signBaseService.deleteById(id));
    }

    @Log(title = "评标基地", businessType = "导入")
    @ApiOperation(value = "工程服务抽取方方案导入", notes = "工程服务抽取方方案导入")
    @PostMapping("/gcImport")
    public CommonResult importProject(MultipartFile file, HttpSession session, String baseName) throws Exception {
        InputStream inputStream = file.getInputStream();
        List<GCBaseVo> list =
                EasyExcel.read(inputStream).head(GCBaseVo.class).sheet().doReadSync();
        List<GCBaseVo> signBase = signBaseService.createSignBase(list, baseName);
        // 清空之前的缓存数据
        session.removeAttribute("gcBaseData");
        // 将 signBase 存入 session 缓存中
        session.setAttribute("gcBaseData", signBase);
        globalDataStore.setGcBaseData(signBase);
        return CommonResult.success();
    }


    @Log(title = "评标基地", businessType = "导出")
    @ApiOperation(value = "工程服务抽取方案导出", notes = "工程服务抽取方案导出")
    @PostMapping("/gcExport")
    public void gcExport(HttpServletResponse response, HttpSession session) {
//        List<GCBaseVo> list = (List<GCBaseVo>) session.getAttribute("gcBaseData");
        List<GCBaseVo> list = globalDataStore.getGcBaseData();
        if (list == null) {
            throw new CommonException(CommonConstants.ERROR, "文件上传失败");
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            String infoName = "工程服务基地选址方案" + "-" + timeStr();
            fileName = URLEncoder.encode(infoName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            HorizontalCellStyleStrategy styleBorder =
                    ExcelStyleUtils.createStyleBorder((short) 10, "宋体", (short) 10, "宋体");
            EasyExcel.write(outputStream, GCBaseVo.class)
                    .registerWriteHandler(new GcSignBaseHandlerColour(list))
                    .registerWriteHandler(new GcSignBaseHandler(list))
                    .registerWriteHandler(styleBorder)
                    .sheet("工程服务基地选址方案").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(CommonConstants.ERROR, "工程服务基地选址方案导出失败");
        }
    }


    @Log(title = "评标基地", businessType = "导入")
    @ApiOperation(value = "基建抽取方案导入", notes = "基建抽取方案导入")
    @PostMapping("/jjImport")
    public CommonResult jjImport(MultipartFile file, HttpSession session, String baseName) throws Exception {
        InputStream inputStream = file.getInputStream();
        List<JjProgectVo> list =
                EasyExcel.read(inputStream).head(JjProgectVo.class).sheet().doReadSync();
        List<JjProgectVo> signBase = signBaseService.createJjSignBase(list, baseName);
        // 清空之前的缓存数据
        session.removeAttribute("jjBaseData");
        // 将 signBase 存入 session 缓存中
        session.setAttribute("jjBaseData", signBase);
        jjGlobalDataStore.setGcBaseData(signBase);
        return CommonResult.success();
    }

    @Log(title = "评标基地", businessType = "导出")
    @ApiOperation(value = "基建抽取方案导出", notes = "基建抽取方案导出")
    @PostMapping("/jjExport")
    public void jjExport(HttpServletResponse response, HttpSession session) {
//        List<JjProgectVo> list = (List<JjProgectVo>) session.getAttribute("jjBaseData");
        List<JjProgectVo> list = jjGlobalDataStore.getGcBaseData();
        if (list == null) {
            throw new CommonException(CommonConstants.ERROR, "文件上传失败");
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            String infoName = "基建基地选址方案" + "-" + timeStr();
            fileName = URLEncoder.encode(infoName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            HorizontalCellStyleStrategy styleBorder =
                    ExcelStyleUtils.createStyleBorder((short) 10, "宋体", (short) 10, "宋体");
            EasyExcel.write(outputStream, JjProgectVo.class)
                    .registerWriteHandler(new JJProgectWriteHandlerColour(list))
                    .registerWriteHandler(new JJProgectWriteHandler(list))
                    .registerWriteHandler(styleBorder)
                    .sheet("基建基地选址方案").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(CommonConstants.ERROR, "基建基地选址方案导出失败");
        }
    }

    @Log(title = "评标基地", businessType = "导入")
    @ApiOperation(value = "物资抽取方案导入", notes = "物资抽取方案导入")
    @PostMapping("/wzImport")
    public CommonResult wzImport(MultipartFile file, HttpSession session, String baseName) throws Exception {
        InputStream inputStream = file.getInputStream();
        List<WzBaseVo> list =
                EasyExcel.read(inputStream).head(WzBaseVo.class).sheet().doReadSync();
        List<WzBaseVo> signBase = signBaseService.createWzSignBase(list, baseName);
        // 清空之前的缓存数据
        session.removeAttribute("wzBaseData");
        // 将 signBase 存入 session 缓存中
        session.setAttribute("wzBaseData", signBase);
        wzGlobalDataStore.setGcBaseData(signBase);
        return CommonResult.success();
    }

    @Log(title = "评标基地", businessType = "导出")
    @ApiOperation(value = "物资抽取方案导出", notes = "物资抽取方案导出")
    @PostMapping("/wzExport")
    public void wzExport(HttpServletResponse response, HttpSession session) {
//        List<WzBaseVo> list = (List<WzBaseVo>) session.getAttribute("wzBaseData");
        List<WzBaseVo> list = wzGlobalDataStore.getGcBaseData();
        if (list == null) {
            throw new CommonException(CommonConstants.ERROR, "文件上传失败");
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            String infoName = "物资基地选址方案" + "-" + timeStr();
            fileName = URLEncoder.encode(infoName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            HorizontalCellStyleStrategy styleBorder =
                    ExcelStyleUtils.createStyleBorder((short) 10, "宋体", (short) 10, "宋体");
            EasyExcel.write(outputStream, WzBaseVo.class)
                    .registerWriteHandler(new WzSignBaseHandlerColour(list))
                    .registerWriteHandler(new WzSignBaseHandler(list))
                    .registerWriteHandler(styleBorder)
                    .sheet("物资基地选址方案").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(CommonConstants.ERROR, "物资基地选址方案");
        }
    }

    public static String timeStr() {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
        // 将当前时间格式化为字符串
        String formattedTime = currentTime.format(formatter);
        return formattedTime;
    }
}
